var authorityLabelMap = {
    defaultValue: 1,
    order: 2,
    report: 3,
    room: 4
};
var authorityValueMap = {
    vipControl: 17,
    vipSetting: 18,
    dirty: 11,
    roomStatus: 1
};
var hotelRoomAuthorityTemplate = $('#hotelRoomAuthorityTemplate'),
    roomTypeAuthorityTemplate = $('#roomTypeAuthorityTemplate'),
    roomAuthorityTemplate = $('#roomAuthorityTemplate');


//处理提交表单返回的数据
var sendMobileSuccessCallback = function(data) {
    formInlineRight($('#verifyVcodeTrigger'));
    timeDisplay($('#verifyVcodeTrigger'), 60);
};
var sendNewMobileSuccessCallback = function(data) {
    formInlineRight($('#newVcodeTrigger'));
    timeDisplay($('#newVcodeTrigger'), 60);
};
var sendMobileErrorCallback = function(data) {
    // $(this).removeAttr('disabled');
    if (typeof data.responseJSON == 'undefined') {
        formInlineTip($('#submitVerifyMobile'), lang('tip.networkPoor'), 0);
    } else {
        formInlineTip($('#submitVerifyMobile'), data.responseJSON.info, 0);
    }
};
var verifyWithMobileSuccessCallback = function(data) {
    formInlineRight($('#submitVerifyMobile'));
    $('#verifyMobileForm').hide();
    $('#changeMobileForm').removeClass('hidden');
    $('#submitVerifyMobile').addClass('hidden');
    $('#submitChangeMobile').removeClass('hidden'); //  $("#submitVerifyMobile").attr("disabled", false);
};
var verifyWithMobileErrorCallback = function(data) {
    //  $("#submitVerifyMobile").attr("disabled", false);
    if (typeof data.responseJSON == 'undefined') {
        formInlineTip($('#submitVerifyMobile'), lang('tip.networkPoor'), 0);
    } else {
        formInlineTip($('#submitVerifyMobile'), data.responseJSON.info, 0);
    }
};
var loadAuthoritySuccessCallback = function(data) {
    //清除选中数据
    $('#authorityModal').find('input[type="checkbox"]').prop('checked', false);
    var authorityData = data.data;
    for (var i = 0; i < authorityData.length; i++) {
        for (var j = 0; j < authorityData[i].authoritys.length; j++) {
            $('input[type=checkbox].hotel[value=' + authorityData[i].hotelId + ']').prop('checked', true);
            $('#hotel_' + authorityData[i].hotelId).find('.authority[value=' + authorityData[i].authoritys[j].hotelauthority_id + ']').prop('checked', true);
        }
    }
};
var loadAuthorityErrorCallback = function(data) {};
var checkUserSuccessCallback = function(data) {
    $('#addName').val(data.data.name);
    $('#addName').attr('disabled', 'disabled');
};
var checkUserErrorCallback = function(data) {
    $('#addName').val('');
    $('#addName').removeAttr('disabled');
};
$(function() {
    //编辑主账户
    $('#infoModal').on('show.bs.modal', function(e) {
        var triggerId = $(e.relatedTarget);
        $('#editName').val(triggerId.data('name'));
        $('#submitInfo').attr('data-value', triggerId.data('id'));
    });
    //修改信息对话框
    $('#infoModal').inputValidate({
        submit: {
            query: '#submitInfo'
        },
        inputs: [{
            query: '#editName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('tip.name'),
            emptyMessage: lang('tip.nameNull')
        }]
    });
    $('#submitInfo').on('successSubmit.amos.inputValidate', function(e) {
        var submitBtn = $(this);
        var params = {};
        params.name = $('#editName').val();
        params.head = $('#uploadPicture').val();
        ajaxRequest('/Home/Account/updateUserInfo', params, 'post', null, null, submitBtn);
    });
	/*$('.applyNormal').click(function(){
		var submitBtn = $(this);
		ajaxRequest('/Home/Account/applyNormal', null, 'post', function(data, obj){
			obj.text(lang('apply'));
			obj.attr('disabled', true);
		}, null, submitBtn);
	})*/
    // 删除子账号，显示账号和姓名
    $('#deleteModal').on('show.bs.modal', function(e) {
        var triggerTd = $(e.relatedTarget).parents('td');
        var account = triggerTd.data('mobile');
        var name = triggerTd.data('name');
        $('#deleteModal .account').html(account);
        $('#deleteModal .name').html(name);
        $('#submitDelete').data('value', triggerTd.parent().data('value'));
    });
    //更换密码
    $('#changeMobileModal').on('show.bs.modal', function(e) {
        var triggerTd = $(e.relatedTarget);
        formInlineRight($('#verifyMobileCode'));
        formInlineRight($('#submitVerifyMobile'));
        formInlineRight($('#newMobile'));
        formInlineRight($('#newMobileCode'));
        formInlineRight($('#submitChangeMobile'));
        $('#verifyMobile').val(triggerTd.data('mobile'));
    });
    //添加账号
    $('#addModal').inputValidate({
        submit: {
            query: '#submitAdd'
        },
        inputs: [{
            query: '#addMobile',
            regexp: window.commonRegexp.mobile,
            message: lang('tip.mobile'),
            emptyMessage: lang('tip.mobileNull')
        }, {
            query: '#addName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('tip.name'),
            emptyMessage: lang('tip.nameNull')
        }]
    });
    $('#changePasswordModal').inputValidate({
        submit: {
            query: '#submitChangePassword'
        },
        inputs: [{
            query: '#requestPassword',
            regexp: window.commonRegexp.password,
            message: lang('tip.password'),
            emptyMessage: lang('tip.passwordNull')
        }, {
            query: '#requestNewPassword',
            regexp: window.commonRegexp.password,
            message: lang('tip.password'),
            emptyMessage: lang('tip.passwordNull')
        }, {
            query: '#requestConfirmNew',
            regexp: window.commonRegexp.password,
            message: lang('tip.password'),
            emptyMessage: lang('tip.passwordNull')
        }, {
            query: '#requestVcode',
            regexp: window.commonRegexp.vcode,
            message: lang('tip.verification'),
            emptyMessage: lang('tip.verificationNull')
        }]
    });
    $('#submitChangePassword').on('successSubmit.amos.inputValidate', function(e) {
        var submitBtn = $(this);
        //检查两次输入密码是否正确
        if ($('#requestConfirmNew').val() != $('#requestNewPassword').val()) {
            formInlineTip($('#submitChangePassword'), lang('tip.newPassword'));
            return false;
        }
        var params = {};
        params.oldPassword = $('#requestPassword').val();
        params.newPassword = $('#requestConfirmNew').val();
        params.vcode = $('#requestVcode').val();
        ajaxRequest('/Home/Account/updatePassword', params, 'post', null, function(error) {
            if (error.responseJSON === undefined) {
                formInlineTip(submitBtn, lang('tip.server'));
            } else {
                formInlineTip(submitBtn, error.responseJSON.info);
            }
            refreshVcode();
            submitBtn.removeAttr('disabled');
        }, submitBtn);
    });
    //更换手机号
    //changeMobileModal
    $('#changeMobileModal').inputValidate({
        submit: {
            query: '#submitVerifyMobile'
        },
        inputs: [{
            query: '#verifyMobileCode',
            regexp: window.commonRegexp.numbervcode6,
            message: lang('tip.verification6'),
            emptyMessage: lang('tip.messages')
        }]
    });
    $('#submitAdd').on('successSubmit.amos.inputValidate', function(e) {
        var submitBtn = $(this);
        // submitBtn.attr('disabled', true);
        var params = {};
        params.mobile = $('#addMobile').val();
        params.name = $('#addName').val();
        params.hotel = window.currentHotel;
        params.areaCode = $('#addModal .areaCodeValue').text().trim();
        ajaxRequest('/Home/Account/addSub', params, 'post', null, null, submitBtn);
    });
    $('#submitDelete').on('click', function(e) {
        var submitBtn = $(this);
        //   submitBtn.attr('disabled', true);
        var params = {};
        params.account = submitBtn.data('value');
        params.hotel = window.currentHotel;
        ajaxRequest('/Home/Account/deleteSub', params, 'post', function() {
            var loopManagerId = 0;
            for (var i = window.currentManagers.length - 1; i >= 0; i--) {
                loopManagerId = parseInt(window.currentManagers[i].id);
                if (loopManagerId === params.account) {
                    window.currentManagers.splice(i, 1);
                    $('#tabSwitchGroup .btn-group-tab.btn-primary').trigger('click');
                    break;
                }
            }
            $('#deleteModal').modal('hide');
        }, null, submitBtn);
    });
    $('#verifyVcodeTrigger').on('click', function(e) {
        e.preventDefault();
        if ($(this).attr('disabled') !== undefined) {
            return false;
        }
        //  $(this).attr('disabled', true);
        var params = {};
        ajaxRequest('/Home/Account/sendMobile', params, 'post', sendMobileSuccessCallback, sendMobileErrorCallback, $(this));
    });
    $('#submitVerifyMobile').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        if ($(this).attr('disabled') !== undefined) {
            return false;
        }
        // $(this).attr('disabled', true);
        var params = {};
        params.vcode = $('#verifyMobileCode').val();
        ajaxRequest('/Home/Account/verifyWithMobile', params, 'post', verifyWithMobileSuccessCallback, verifyWithMobileErrorCallback);
    });
    $('#changeMobileForm').inputValidate({
        submit: {
            query: '#newVcodeTrigger'
        },
        inputs: [{
            query: '#newMobile',
            regexp: window.commonRegexp.mobile,
            message: lang('tip.mobile'),
            emptyMessage: lang('tip.mobileNull')
        }]
    });
    // 新手机号码发送短信验证
    $('#newVcodeTrigger').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        if ($(this).attr('disabled') !== undefined) {
            return false;
        }
        //  $(this).attr('disabled', true);
        var params = {};
        params.mobile = $('#newMobile').val();
        params.areaCode = $('#changeMobileForm .areaCodeValue').text().trim();
        ajaxRequest('/Home/Account/sendMobileNew', params, 'post', sendNewMobileSuccessCallback, null, $(this));
    });
    $('#changeMobileModalDialog').inputValidate({
        submit: {
            query: '#submitChangeMobile'
        },
        inputs: [{
            query: '#newMobile',
            regexp: window.commonRegexp.mobile,
            message: lang('tip.mobile'),
            emptyMessage: lang('tip.mobileNull')
        }, {
            query: '#newMobileCode',
            regexp: window.commonRegexp.numbervcode6,
            message: lang('tip.verification6'),
            emptyMessage: lang('tip.messages')
        }]
    });
    //验证新的手机号
    $('#submitChangeMobile').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        if ($(this).attr('disabled') !== undefined) {
            return false;
        }
        // $(this).attr('disabled', true);
        var params = {};
        params.vcode = $('#newMobileCode').val();
        params.mobile = $('#newMobile').val();
        params.areaCode = $('#changeMobileForm .areaCodeValue').text().trim();
        ajaxRequest('/Home/Account/verifyWithMobileNew', params, 'post', null, null, $(this));
    });
    // 权限对话框显示
    $('#authorityModal').on('show.bs.modal', function(e) {
        var triggerTd = $(e.relatedTarget).parents('td');
        var account = triggerTd.parent().data('value');
        var submitBtn = $('#submitAuthority');
        submitBtn.data('value', triggerTd.parent().data('value'));
        //获取用户权限数据
        var params = {};
        params.account = account;
        ajaxRequest('/Home/Account/getAuthority', params, 'post', loadAuthoritySuccessCallback, null, submitBtn);
    });
    //更改权限数据
    $('#submitAuthority').on('click', function(e) {
        e.preventDefault();
        if ($(this).attr('disabled') !== undefined) {
            return false;
        }
        //获取客栈权限对象
        //  $(this).attr('disabled', true);
        var submitBtn = $(this);
        var params = {};
        params.account = submitBtn.data('value');
        params.authority = [];
        $('#authorityModal  .hotelAuthority').each(function(index, element) {
            var authority = {};
            var hotelTr = $(this);
            authority.hotelId = hotelTr.find('.hotel').val();
            var subAuth = [];
            hotelTr.find('.authority').each(function() {
                if ($(this).prop('checked')) {
                    subAuth.push($(this).val());
                }
            });
            authority.authorityStr = subAuth.join(',');
            params.authority.push(authority);
        });

        ajaxRequest('/Home/Account/setAuthority', params, 'post', function(data) {
            var hasAuthorityHotels = [];
            $.each(params.authority, function(key, authorityItem) {
                if (authorityItem.authorityStr === '') {
                    return true;
                }
                hasAuthorityHotels.push(authorityItem.hotelId);
            });
            var loopManagerId = 0;
            for (var i = window.currentManagers.length - 1; i >= 0; i--) {
                loopManagerId = parseInt(window.currentManagers[i].id);
                if (loopManagerId === params.account) {
                    window.currentManagers[i].hotels = hasAuthorityHotels;
                    $('#tabSwitchGroup .btn-group-tab.btn-primary').trigger('click');
                    break;
                }
            }
            $('#authorityModal').modal('hide');
        }, null, submitBtn);
    });
    window.accountConstant = {
        'cover': 1,
    };
    $('#showOrganizationNoContainer').on('click',function(){
        $('#submitInfoPicture').data('config', 'default').data('type', window.accountConstant.cover);
        $('#pictureInfoSelector').trigger('click'); 
    });
    //设置客栈全选或全不选
    $('#accountAuthority-container').delegate('.hotel', 'click', function() {
        //全选中
        if ($(this).prop('checked') === true) {
            $(this).parents('.hotelAuthority').find('.authority').prop('checked', true);
        } else {
            $(this).parents('.hotelAuthority').find('.authority').prop('checked', false);
        }
    });
    $('#accountAuthority-container').on('click', '.authority', function() {
        var checkbox = $(this);
        var permissionBox = checkbox.parents('.permission');
        var permissionLabelValue = checkbox.parents('.allauthority').attr('value');
        var hotelCheckbox;
        if (checkbox.prop('checked') === true) {
            if (permissionBox.find('.authority:checked').length !== 0) {
                hotelCheckbox = permissionBox.parents('.hotelAuthority').find('.hotel');
                hotelCheckbox.prop('checked', true);
            }
            // 脏房被按了,查看房态跟着checked
            if (checkbox.val() == authorityValueMap.dirty || permissionLabelValue == authorityLabelMap.room) {
                permissionBox.find('input.authority[type=checkbox][value=' + authorityValueMap.roomStatus + ']').prop('checked', true);
            }
            // 订单处理被按了,查看房态and查看订单跟着checked
            if (permissionLabelValue == authorityLabelMap.order) {
                permissionBox.find('.allauthority[value=' + authorityLabelMap.defaultValue + '] .authority').each(function() {
                    $(this).prop('checked', true);
                });
            }
            // 会员设置被按了,会员管理跟着checked
            if (checkbox.val() == authorityValueMap.vipSetting) {
                permissionBox.find('input.authority[type=checkbox][value=' + authorityValueMap.vipControl + ']').prop('checked', true);
            }
        } else {
            if (permissionBox.find('.authority:checked').length === 0) {
                hotelCheckbox = permissionBox.parents('.hotelAuthority').find('.hotel');
                hotelCheckbox.prop('checked', false);
            }
            // 默认的两个被取消,订单跟着取消
            if (permissionLabelValue == authorityLabelMap.defaultValue) {
                permissionBox.find('.allauthority[value=' + authorityLabelMap.order + '] .authority').each(function() {
                    $(this).prop('checked', false);
                });
                // 查看房态被取消,脏房跟着取消
                if (checkbox.val() == authorityValueMap.roomStatus) {
                    permissionBox.find('.allauthority[value=' + authorityLabelMap.room + '] .authority').each(function() {
                        $(this).prop('checked', false);
                    });
                }
            }
            // 会员管理被取消,会员设置跟着checked
            if (checkbox.val() == authorityValueMap.vipControl) {
                permissionBox.find('input.authority[type=checkbox][value=' + authorityValueMap.vipSetting + ']').prop('checked', false);
            }
        }
    });
    $('#addMobile').blur(function() {
        $('#ajaxSeachLoad').html('');
        var params = {};
        params.mobile = $(this).val();
        params.areaCode = $('#addModal .areaCodeValue').text().trim();
        ajaxRequest('/Home/Account/checkUserExist', params, 'post', checkUserSuccessCallback, checkUserErrorCallback);
    });
    //初始化主账户推广链接信息
    ajaxRequest('/Home/Account/publicLinkInfo', {}, 'post', function(data) {
        var popularizeInfo = data.data;
        $('#popularizeLink').html(popularizeInfo.link);
        $('#popularizeName').val(popularizeInfo.name);
        if (popularizeInfo.imageUrl !== null && popularizeInfo.imageUrl.length > 0) {
            refreshPopularizeImage(popularizeInfo.imageUrl);
        }
        var canvasContainer = $('#popularizeLinkQRCode');
        canvasContainer.html('');
        canvasContainer.qrcode({
            width: 134,
            height: 134,
            text: popularizeInfo.link
        });
    }, function(error) {});
    //修改主账号推广链接信息对话框
    $('#popularizeModal').inputValidate({
        submit: {
            query: '#submitPopularizeInfo'
        },
        inputs: [{
            query: '#popularizeName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('tip.popularize'),
            emptyMessage: lang('tip.popularizeNull')
        }]
    });
    $('#popularizeModal').on('show.bs.modal', function(e) {
        formInlineRight($('#popularizeName'));
        formInlineRight($('#submitPopularizeInfo'));
    });
    $('#popularizeModal').on('successSubmit.amos.inputValidate', function(e) {
        var submitBtn = $('#submitPopularizeInfo');
        var params = {};
        params.name = $('#popularizeName').val();
        params.imageUrl = submitBtn.data('image');
        ajaxRequest('/Home/Account/savePublicLinkInfo', params, 'post', function() {
            formInlineTip(submitBtn, lang('successfullySet'), 1);
        }, null, submitBtn);
    });

    $('#popularizeModal .picuture-upload, #popularizeModal .picture-re-upload').on('click', function(e) {
        $('#submitPicture').data('config', 'publicLink').data('type', window.accountConstant.popularize);
        $('#pictureSelector').trigger('click');
    });
    window.accountConstant = { 'popularize': 1 };

    // 权限对话框显示
    $('#roomAuthorityModal').on('show.bs.modal', function(e) {
        var triggerTd = $(e.relatedTarget).parents('td');
        var account = triggerTd.parent().data('value');
        $('#submitRoomAuthority').attr('data-value', account);
        //获取用户权限数据
        var params = {};
        params.account = account;
        ajaxRequest('/Home/Account/roomAuthority', params, 'post', function(data) {
            $('#roomAuthority-container').html('');
            $.each(data.data, function(key, hotel) {
                hotelRoomAuthorityTemplateClone = $(hotelRoomAuthorityTemplate.clone().html());
                hotelRoomAuthorityTemplateClone.find('.hotelName').text(hotel.name);
                hotelRoomAuthorityTemplateClone.find('.hotel').data('value', hotel.hotel);
                var hasRoom = false;
                $.each(hotel.roomType, function(key, roomType) {
                    roomTypeAuthorityTemplateClone = $(roomTypeAuthorityTemplate.clone().html());
                    roomTypeAuthorityTemplateClone.find('.control-label').text(roomType.name);
                    var roomTypeAuthority = false;
                    $.each(roomType.room, function(key, room) {
                        hasRoom = true;
                        roomAuthorityTemplateClone = $(roomAuthorityTemplate.clone().html());
                        roomAuthorityTemplateClone.find('.control-label').text(room.name);
                        var roomAuthority = room.enable == 1 ? true : false;
                        roomAuthorityTemplateClone.find('.roomAuthority').get(0).checked = roomAuthority;
                        roomAuthorityTemplateClone.find('.roomAuthority').data('value', room.room);

                        // 赋值房型是否有选择
                        roomTypeAuthority = roomTypeAuthority || roomAuthority;
                        roomTypeAuthorityTemplateClone.find('.allauthority').append(roomAuthorityTemplateClone);
                    });

                    roomTypeAuthorityTemplateClone.find('.roomTypeAuthority').prop('checked', roomTypeAuthority);
                    hotelRoomAuthorityTemplateClone.find('.permission').append(roomTypeAuthorityTemplateClone);
                });
                // 查看是否已经全选
                var allChecked = hotelRoomAuthorityTemplateClone.find('.roomAuthority').not('input:checked').length == 0 ? true : false;
                hotelRoomAuthorityTemplateClone.find('.hotel').prop('checked', (allChecked && hasRoom));

                $('#roomAuthority-container').append(hotelRoomAuthorityTemplateClone);
            });
        }, null, $('#submitRoomAuthority'));
    });
    //更改房间权限数据
    $('#submitRoomAuthority').on('click', function(e) {
        e.preventDefault();
        if ($(this).attr('disabled') !== undefined) {
            return false;
        }
        var params = {};
        params.account = $(this).attr('data-value');
        params.authority = [];
        $('#roomAuthorityModal  .hotelRoomAuthority').each(function(index, element) {
            var hotel = $(element),
                hotelAuthority = {
                    hotel: hotel.find('.hotel').data('value'),
                    room: [],
                };
            hotel.find('.roomAuthority:checked').each(function(index, room) {
                var room = $(room);
                hotelAuthority.room.push(room.data('value'));
            });
            hotelAuthority.room = hotelAuthority.room.join(',');
            params.authority.push(hotelAuthority);
        });
        ajaxRequest('/Home/Account/setRoomAuthority', params, 'post', function(data) {
            $('#roomAuthorityModal').modal('hide');
        }, null, $(this));
    });
    // 房型权限模态框房型checkbox点击
    $('#roomAuthorityModal').on('change', '.roomTypeAuthority', function(e) {
        e.preventDefault();
        var checkbox = $(e.target),
            checked = checkbox.prop('checked'),
            parentHotel = checkbox.parents('.hotelRoomAuthority');
        checkbox.parents('.roomTypeAuthorityItem').find('.roomAuthority').prop('checked', checked);
        checkbox.prop('checked', checked);

        // 检查是否需要选中全选
        var hasRoom = parentHotel.find('.roomAuthority').length != 0 ? true : false,
            allChecked = parentHotel.find('.roomAuthority').not('input:checked').length == 0 ? true : false;
        parentHotel.find('.hotel').prop('checked', (hasRoom && allChecked));
    });
    // 房间权限模态框房型checkbox点击
    $('#roomAuthorityModal').on('change', '.roomAuthority', function(e) {
        e.preventDefault();
        var checkbox = $(e.target),
            checked = checkbox.prop('checked'),
            parentHotel = checkbox.parents('.hotelRoomAuthority');
        checkbox.prop('checked', checked);

        var hasChecked = checkbox.parents('.roomTypeAuthorityItem').find('.roomAuthority:checked').length > 0 ? true : false;
        checkbox.parents('.roomTypeAuthorityItem').find('.roomTypeAuthority').prop('checked', hasChecked);

        // 检查是否需要选中全选
        var hasRoom = parentHotel.find('.roomAuthority').length != 0 ? true : false,
            allChecked = parentHotel.find('.roomAuthority').not('input:checked').length == 0 ? true : false;
        parentHotel.find('.hotel').prop('checked', (hasRoom && allChecked));
    });
    // 房间权限模态框全选checkbox点击
    $('#roomAuthorityModal').on('change', '.hotel', function(e) {
        e.preventDefault();
        var checkbox = $(e.target),
            parent = checkbox.parents('.hotelRoomAuthority'),
            checked = checkbox.prop('checked');
        checkbox.prop('checked', checked);

        parent.find('.roomTypeAuthority').prop('checked', checked);
        parent.find('.roomAuthority').prop('checked', checked);
    });

    var initGroupMembersTable = function(members) {
        if (members.length > 0) {
            $('#managerErrorInfoContainer').addClass('hidden');
            $('#accounts-table').removeClass('hidden');
            var groupMemberTemplate = $($('#templateGroupMemberTr').clone().html());
            var groupMemberHTMLs = '';
            $.each(members, function(key, data) {
                groupMemberTemplate.attr('data-value', data.id);
                groupMemberTemplate.find('[tag="name"]').html(data.name);
                groupMemberTemplate.find('[tag="mobile"]').html(data.mobile);
                groupMemberTemplate.find('[tag="group"]').html('');
                groupMemberTemplate.find('[tag="group"]').html(window.currentGroupNames[data.groupId]);
                var hotelNames = [];
                for (var i = 0; i < data.hotels.length; i++) {
                    hotelNames.push(window.navbarHotels[data.hotels[i]].name);
                }
                groupMemberTemplate.find('[tag="authority"]').html(hotelNames.join('，'));
                groupMemberTemplate.find('[tag="operation"]').attr('data-name', data.name);
                groupMemberTemplate.find('[tag="operation"]').attr('data-mobile', data.mobile);
                groupMemberHTMLs += groupMemberTemplate.prop('outerHTML');
            });
            $('#accounts-table tbody').html(groupMemberHTMLs);
        } else {
            $('#managerErrorInfoContainer').removeClass('hidden');
            $('#accounts-table').addClass('hidden');
        }
    };
    // 子管理员分组需求
    ajaxRequest('/Home/Account/info', {}, 'post', function(data) {
        $('#roomAuthorityModal').modal('hide');
        window.currentManagers = data.data.account;
        window.currentGroups = data.data.group;
        window.currentGroupNames = {};
        $.each(window.currentGroups, function(key, data) {
            window.currentGroupNames[data.id] = data.name;
        });
        if (window.currentManagers.length === 0 || window.currentGroups.length === 0) {
            $('#groupMemberModalTrigger').addClass('hidden');
        }
        initGroupMembersTable(window.currentManagers);

        // 初始化编辑组名模态框
        $('#groupNameModal').on('show.bs.modal', function() {
            var groupNameHTMLs = '';
            var groupInputTemplate = $($('#templateGroup').clone().html());
            $.each(window.currentGroups, function(key, data) {
                groupInputTemplate.find('.editGroupName').attr('data-value', data.id);
                groupInputTemplate.find('.editGroupName').attr('value', data.name);
                groupNameHTMLs += groupInputTemplate.prop('outerHTML');
            });
            $('#groupNameForm .editGroupNameContainer').remove();
            $('#groupNameForm .addGroupContainer').before($(groupNameHTMLs));
            if (window.currentGroups.length >= 5) {
                $('#groupNameForm .addGroupContainer').addClass('hidden');
            }
        }).on('click', '.removeGroupName', function(e) {
            e.preventDefault();
            $(this).parents('.editGroupNameContainer').remove();
            $('#groupNameForm .addGroupContainer').removeClass('hidden');
        });

        $('#addGroup').on('click', function(e) {
            e.preventDefault();
            var hasGroup = $('#groupNameForm .editGroupNameContainer').length;
            if (hasGroup >= 4) {
                $('#groupNameForm .addGroupContainer').addClass('hidden');
            }

            if (hasGroup < 5) {
                $('#groupNameForm .addGroupContainer').before($($('#templateGroup').clone().html()));
            }
        });

        $('#groupNameModal').inputValidate({
            submit: {
                query: '#submitGroupName'
            },
            inputs: [{
                query: '.editGroupName',
                regexp: /.{1,15}/,
                message: lang('tip.groupName'),
                emptyMessage: lang('tip.groupNameNull')
            }]
        });

        $('#submitGroupName').on('successSubmit.amos.inputValidate', function(e) {
            var submitBtn = $(this);
            var groups = [];
            $('#groupNameForm .editGroupName').each(function(key, item) {
                var id = $(item).data('value');
                groups.push({ id: id === undefined ? 0 : id, name: $(item).val() });
            });
            ajaxRequest('/Home/Group/save', { group: groups }, 'POST', null, null, submitBtn);
        });


        // 初始化组tab以及选择组下拉框
        var groupTabs = '';
        var groupTabTemplate = $($('#templateGroupTab').clone().html());
        var groupOptions = '';
        $.each(window.currentGroups, function(key, data) {
            groupTabTemplate.attr('data-value', data.id);
            groupTabTemplate.html(data.name);
            groupTabs += groupTabTemplate.prop('outerHTML');
            groupOptions += '<option value="' + data.id + '">' + data.name + '</option>';
        });
        $('#groupMemberBelong').html(groupOptions);
        $('#tabSwitchGroup .btn-group-tab').eq(0).after($(groupTabs));
        $('#tabSwitchGroup .btn-group-tab').on('click', function(e) {
            e.preventDefault();
            var tab = $(this);
            tab.addClass('btn-primary').siblings().removeClass('btn-primary');
            var currentGroupId = tab.data('value');
            // 全部
            if (currentGroupId === 0) {
                initGroupMembersTable(window.currentManagers);
                return true;
            }
            // 显示某组
            var members = [];
            for (var i = 0; i < window.currentManagers.length; i++) {
                if (parseInt(window.currentManagers[i].groupId) !== currentGroupId) {
                    continue;
                }
                members.push(window.currentManagers[i]);
            }
            initGroupMembersTable(members);
        });

        // 初始化编辑组成员模态框
        $('#groupMemberModal').on('show.bs.modal', function(e) {
            formInlineRight($('#submitGroupMember'));
            $('#groupMemberBelong').trigger('change');
        });
        // 监听下拉框变化组内成员的选择状态
        $('#groupMemberBelong').on('change', function(e) {
            var selectedValue = parseInt($(this).val());
            var template = $($('#templateGroupMember').clone().html());
            var memberHTMLs = '';
            $.each(window.currentManagers, function(key, data) {
                var templateCheckbox = template.find('input');
                var memberBelongGroup = parseInt(data.groupId);
                if (memberBelongGroup === 0) {
                    templateCheckbox.removeAttr('disabled');
                    templateCheckbox.attr('checked', false);
                } else if (memberBelongGroup === selectedValue) {
                    templateCheckbox.removeAttr('disabled');
                    templateCheckbox.attr('checked', true);
                } else {
                    templateCheckbox.attr('disabled', true);
                    templateCheckbox.attr('checked', false);
                }
                templateCheckbox.attr('data-value', data.id);
                template.find('.checkbox-label').html(data.name);
                memberHTMLs += template.prop('outerHTML');
            });
            $('#groupMembers').html(memberHTMLs);
            componentHandler.upgradeAllRegistered();
        });
        $('#submitGroupMember').on('click', function(e) {
            e.preventDefault();
            var submitBtn = $(this);
            var currentGroupId = parseInt($('#groupMemberBelong').val());
            var inGroupManager = [];
            var notInGroupManager = [];
            $.each($('#groupMembers .checkbox-input'), function(key, item) {
                var itemObj = $(item);
                if (itemObj.prop('checked')) {
                    inGroupManager.push(itemObj.data('value'));
                } else {
                    notInGroupManager.push(itemObj.data('value'));
                }
            });
            ajaxRequest('/Home/Group/saveAccount', { groupId: currentGroupId, inGroupAccountId: inGroupManager, notInGroupAccountId: notInGroupManager }, 'POST', function(data, submitBtn) {

                var memberGroupId = 0;
                var memberId = 0;
                for (var i = 0; i < window.currentManagers.length; i++) {
                    memberGroupId = parseInt(window.currentManagers[i].groupId);
                    // 先排除其他组
                    if (memberGroupId !== 0 && memberGroupId !== currentGroupId) {
                        continue;
                    }

                    memberId = parseInt(window.currentManagers[i].id);
                    if ($.inArray(memberId, inGroupManager) !== -1) {
                        window.currentManagers[i].groupId = currentGroupId;
                    }

                    if ($.inArray(memberId, notInGroupManager) !== -1) {
                        window.currentManagers[i].groupId = 0;
                    }
                }
                formInlineTip(submitBtn, lang('successfullySave'));
                $('#tabSwitchGroup .btn-group-tab.btn-primary').trigger('click');
            }, null, submitBtn);
        });
    }, function(error) {
        var errorContainer = $('#managerErrorInfo');
        errorContainer.html(lang('tip.serverRefresh'));
    });
});
var refreshPopularizeImage = function(url) {
    $('#popularizeModal .picture').css('background-image', 'url(' + url + ')').removeClass('hidden');
    $('#submitPopularizeInfo').data('image', url);
};
var pictureCropperSuccess = function(imageUrl, imageType) {
    switch (imageType) {
        case window.accountConstant.popularize:
            refreshPopularizeImage(imageUrl);
            $('#pictureModal').modal('hide');
            break;
        default:
            break;
    }
};
var pictureInfoCropperSuccess = function (imageUrl, imageType) {
    var submitPicture = $('#submitInfoPicture');
    switch (imageType) {
        case window.accountConstant.cover:
            $('#uploadPicture').val(imageUrl);
            $('.img-certification').attr('src',imageUrl);
            $('#pictureInfoModal').modal('hide');
            break;
        default:
            break;
    }
};